<?php
error_reporting("E_ALL");ini_set("display_errors", 1);
include("include/function.php");
//header("content-Type: application/json; charset=utf-8");
$config = include("config.php");
include("include/".$config['DB_TYPE'].".class.php");
$db = new db;
$db->connect($config['DB_HOST'],$config['DB_USER'],$config['DB_PWD'],$config['DB_NAME'], $config['DB_PCONNECT']);
$post = $_GET;
$id = !empty($post['id'])?intval($post['id']):0;
$sql='select id,host,country_name,updatetime from ollama_domain where status=1 and number=0 and id>'.$id.' order by id limit 2';
$list = $db->get_all($sql);$lastid = 0;
foreach($list as $v){$lastid = $v['id'];
    if($v['updatetime'] && $v['updatetime']>strtotime('today'))continue;
    $url = 'http://'.$v['host'].'/api/tags';
    $res = curlget($url);
    $array = json_decode($res,1);
    $models = $array['models'];
    if(!empty($models)){
        $oldnames_list = $db->get_all("select id,name from ollama_list where host='".$v['host']."'");
        $oldnames=[];foreach($oldnames_list as $v1){$oldnames[]=$v1['name'];}
        $itemmodels=[];
        foreach($models as $val){$itemmodels[$val['model']]=$val['model'];
            if(in_array($val['name'],$oldnames))continue;$oldnames[]=$val['name'];
            $data = [];
            $data['host']=$v['host'];
            $data['country_name']=$v['country_name'];
            $data['name']=$val['name'];
            $data['model']=$val['model'];
            $data['modified_at']=$val['modified_at'];
            $data['size']=$val['size'];
            $data['digest']=$val['digest'];
            $data['details']=json_encode($val['details']);
            $data['addtime']=date('Y-m-d H:i:s');
            
            $insert = "insert into ollama_list(".implode(',',array_keys($data)).") values('".implode("','",$data)."')"; 
            $db->query($insert);
        }
        if($itemmodels){
            $db->query("update ollama_domain set status=1,updatetime=".time().",`models`='".implode(',',$itemmodels)."',`number`='".count($itemmodels)."' where id=".$v['id']);
        }else{
            $db->query('update ollama_domain set status=2,updatetime='.time().' where id='.$v['id']);
        }
    }else{
        $db->query('update ollama_domain set status=2,updatetime='.time().' where id='.$v['id']);
    }
    
}
if($lastid){
    echo $lastid."<script>location.href='?id=".$lastid."'</script>";
}else{
    exit('over');
}


?>